package cn.elwy.rcp.kit.maven;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.eclipse.e4.ui.di.Focus;
import org.eclipse.e4.ui.di.Persist;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;

import cn.elwy.common.util.AssertUtil;
import cn.elwy.common.util.io.FileUtil;
import cn.elwy.rcp.core.model.ui.InputModel;
import cn.elwy.rcp.kit.TableIdConst;
import cn.elwy.rcp.ui.dialog.MsgDialog;
import cn.elwy.rcp.ui.table.TablePane;
import cn.elwy.rcp.ui.table.TablePaneFactory;

public class MavenTool {

	private static final String MAVEN_REPO_PATH = "X:/Repository";
	private static final String ENCODE = "gbk";

	protected Object result;
	protected Shell shell;
	private Text txtXrepository;
	private Text text;
	private DeleteLastUpdatedHandler deleteLastUpdatedHandler;
	private Text jarDirText;
	private Text groupIdText;
	private TablePane tablePane;

	@PostConstruct
	public void createComposite(final Composite parent) {
		parent.setLayout(new GridLayout(1, false));
		// setTitle("Maven安装Jar");
		// setMessage("部署jar包到服务器或者本地");
		// Composite area = (Composite) super.createDialogArea(parent);
		// Composite container = new Composite(area, SWT.NONE);
		// GridLayout gl_container = new GridLayout(1, false);
		// container.setLayout(gl_container);
		// container.setLayoutData(new GridData(GridData.FILL_BOTH));

		TabFolder tabFolder = new TabFolder(parent, SWT.NONE);
		tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

		TabItem tbtmNewItem = new TabItem(tabFolder, SWT.NONE);
		tbtmNewItem.setText("安装JAR包");

		Composite composite = new Composite(tabFolder, SWT.NONE);
		tbtmNewItem.setControl(composite);
		composite.setLayout(new GridLayout(3, false));

		Label lblJar = new Label(composite, SWT.NONE);
		lblJar.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		lblJar.setText("JAR目录：");

		jarDirText = new Text(composite, SWT.BORDER);
		jarDirText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent arg0) {
				String text2 = jarDirText.getText();

				if (AssertUtil.isNotEmpty(text2)) {
					File f = new File(text2);
					List<File> fileList = new ArrayList<File>();
					if (f.isFile()) {
						fileList.add(f);
					} else if (f.isDirectory()) {
						setFileList(f, fileList);
					}
					List<MavenInfo> miList = parser(fileList);
					InputModel im = new InputModel(miList);
					tablePane.setInputModel(im);
				}
			}
		});
		jarDirText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

		Button btnNewButton_1 = new Button(composite, SWT.NONE);
		btnNewButton_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				// 新建文件夹（目录）对话框
				DirectoryDialog folderdlg = new DirectoryDialog(parent.getShell());
				// 设置文件对话框的标题
				folderdlg.setText("选择文件夹");
				// 设置初始路径
				folderdlg.setFilterPath("SystemDrive");
				// 设置对话框提示文本信息
				folderdlg.setMessage("请选择相应的文件夹");
				// 打开文件对话框，返回选中文件夹目录
				String selecteddir = folderdlg.open();
				if (selecteddir == null) {
					return;
				} else {
					jarDirText.setText(selecteddir);
				}
			}
		});
		btnNewButton_1.setText("选择目录");

		Label lblGroupid = new Label(composite, SWT.NONE);
		lblGroupid.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		lblGroupid.setText("GroupId:");

		groupIdText = new Text(composite, SWT.BORDER);
		groupIdText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent arg0) {
				String groupId = groupIdText.getText();
				List<MavenInfo> miList = tablePane.getInputModel().getInput();
				if (groupId == null || groupId.trim().equals("")) {
					jarDirText.setText(jarDirText.getText());
				} else if (miList != null) {
					for (MavenInfo mi : miList) {
						mi.setGroupId(groupId);
					}
					tablePane.refresh();
				}
			}
		});
		groupIdText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		new Label(composite, SWT.NONE);

		Label label = new Label(composite, SWT.NONE);
		label.setText("安装方式：");

		Composite composite_2 = new Composite(composite, SWT.NONE);
		composite_2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		GridLayout gl_composite_2 = new GridLayout(2, false);
		gl_composite_2.marginWidth = 0;
		gl_composite_2.marginHeight = 0;
		composite_2.setLayout(gl_composite_2);

		Button installButton = new Button(composite_2, SWT.RADIO);
		installButton.setText("install");
		installButton.setSelection(true);

		final Button deployButton = new Button(composite_2, SWT.RADIO);
		deployButton.setText("deploy");

		Button btnNewButton_2 = new Button(composite, SWT.NONE);
		btnNewButton_2.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Display.getDefault().asyncExec(new Runnable() {
					@Override
					public void run() {
						boolean isDeploy = deployButton.getSelection();
						final Runtime runtime = Runtime.getRuntime();
						List<MavenInfo> miList = tablePane.getInputModel().getInput();
						for (MavenInfo mi : miList) {
							String createMvnCmd = createMvnCmd(isDeploy, mi.getGroupId(), mi.getArtifactId(), mi.getVersion(),
									mi.getPath());
							final String[] cmds = new String[] { "cmd", "/C", createMvnCmd };
							try {
								Process process = runtime.exec(cmds);
								printResult(process);
							} catch (Exception err) {
								err.printStackTrace();
							}
						}
						MsgDialog.openInformation(shell, "安装Jar包结束！");
					}
				});

			}
		});
		btnNewButton_2.setText("确定");
		// tablePane = new Table(parent, SWT.None);
		tablePane = TablePaneFactory.getTablePane(composite, TableIdConst.MAVEN_INFO_TABLE);
		GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1);
		layoutData.heightHint = 1;
		tablePane.setLayoutData(layoutData);

		TabItem tbtmlastupdated = new TabItem(tabFolder, SWT.NONE);
		tbtmlastupdated.setText("删除lastUpdated");

		Composite composite_1 = new Composite(tabFolder, SWT.NONE);
		tbtmlastupdated.setControl(composite_1);
		composite_1.setLayout(new GridLayout(3, false));

		Label lblNewLabel = new Label(composite_1, SWT.NONE);
		lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		lblNewLabel.setText("Maven本地仓库路径：");

		txtXrepository = new Text(composite_1, SWT.BORDER);
		txtXrepository.setText(MAVEN_REPO_PATH);
		txtXrepository.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

		Button btnNewButton = new Button(composite_1, SWT.NONE);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Display.getCurrent().asyncExec(new Runnable() {
					@Override
					public void run() {
						String text2 = txtXrepository.getText();
						if (text2 != null && !text2.isEmpty()) {
							File file = new File(text2);
							if (file.isDirectory()) {
								deleteLastUpdatedHandler.delFileRecr(file.listFiles(), null);
								deleteLastUpdatedHandler.out("清理lastUpdated完成！");
							}
						}
					}
				});
			}
		});
		btnNewButton.setText("清理lastUpdated");

		text = new Text(composite_1, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI);
		text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));

		deleteLastUpdatedHandler = new DeleteLastUpdatedHandler() {
			@Override
			public void out(String message) {
				text.append(message + "\r\n");
			}
		};
		init();
	}

	private void init() {
		jarDirText.setText("X:/package/bundles");
	}

	protected List<MavenInfo> parser(List<File> fileList) {
		List<MavenInfo> miList = new ArrayList<MavenInfo>();
		for (File file : fileList) {
			String shortFileName = FileUtil.getShortFileName(file);
			int indexOf = shortFileName.indexOf("-");
			if (indexOf < 1) {
				indexOf = shortFileName.indexOf("_");
			}
			String artifactId = shortFileName.substring(0, indexOf);
			String groupId = groupIdText.getText();
			if (AssertUtil.isEmpty(groupId)) {
				groupId = artifactId;
			}
			String version = shortFileName.substring(indexOf + 1);
			MavenInfo mi = new MavenInfo();
			mi.setGroupId(groupId);
			mi.setArtifactId(artifactId);
			mi.setVersion(version);
			mi.setPath(file.getAbsolutePath());
			miList.add(mi);
		}
		return miList;
	}

	private static String createMvnCmd(boolean isDeploy, String groupId, String artifactId, String version, String path) {
		StringBuffer sb = new StringBuffer("mvn ");
		if (isDeploy) {
			sb.append("deploy:deploy");
		} else {
			sb.append("install:install");
		}
		sb.append("-file -DgroupId=").append(groupId).append(" -DartifactId=").append(artifactId).append(" -Dversion=")
				.append(version).append(" -Dpackaging=jar").append(" -Dfile=").append(path);
		return sb.toString();
	}

	protected void setFileList(File file, List<File> list) {
		File[] listFiles = file.listFiles(new FileFilter() {

			@Override
			public boolean accept(File pathname) {
				return pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".jar");
			}
		});
		if (listFiles != null) {
			for (File file2 : listFiles) {
				if (file2.isDirectory()) {
					setFileList(file2, list);
				} else if (file2.isFile()) {
					list.add(file2);
				}
			}
		}
	}

	protected static void printResult(Process process) throws IOException {
		InputStream is = process.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is, ENCODE));
		String lineStr;
		while ((lineStr = br.readLine()) != null) {
			System.out.println(lineStr);
		}
	}

	@Focus
	public void setFocus() {
	}

	@Persist
	public void save() {
	}
}